package com.ljt.yupictureddd.infrastracture.aop;

import com.ljt.yupictureddd.infrastracture.annotation.AuthCheck;
import com.ljt.yupictureddd.infrastracture.exception.ErrorCode;
import com.ljt.yupictureddd.infrastracture.exception.ThrowUtils;
import com.ljt.yupictureddd.domain.user.entity.User;
import com.ljt.yupictureddd.domain.user.valueobject.UserRoleEnums;
import com.ljt.yupictureddd.application.service.UserApplicationService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserApplicationService userApplicationService;

    /**
     * 执行拦截
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doIntercept(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        User loginUser = userApplicationService.getLoginUser(request);
        UserRoleEnums mustRoleEnum = UserRoleEnums.getEnumByValue(mustRole);

//        如果没有权限,放行
        if (mustRoleEnum == null){
            joinPoint.proceed();
        }

//        权限注解写了mustRole，要校验
        UserRoleEnums loginUserEnum = UserRoleEnums.getEnumByValue(loginUser.getUserRole());
//        用户为空,抛出异常
        ThrowUtils.throwIf(loginUserEnum==null, ErrorCode.NO_AUTH_ERROR);
//        必须要有管理员权限的，你是用户，要拒绝
        ThrowUtils.throwIf(UserRoleEnums.ADMIN.equals(mustRoleEnum) && !UserRoleEnums.ADMIN.equals(loginUserEnum),ErrorCode.NO_AUTH_ERROR);
//        通过校验
        return joinPoint.proceed();
    }
}
